package com.servlet;

import com.common.Constant;
import com.ztc.Spider;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by ztc on 16-1-8.下午2:15
 */
public class PingJiao extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Spider spider=(Spider)request.getSession(true).getAttribute("spider");
        String[] cjid=request.getParameterValues("cjid");
        if(cjid==null||spider==null||spider.getScore().length()<20){
            response.sendRedirect("pj.jsp");
        }else {
            for (String id : cjid) {
                HttpPost post = new HttpPost(Constant.tijiaoUrl);
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("cjid", id));
                params.add(new BasicNameValuePair("cpjg", request.getParameter("choose")));
                params.add(new BasicNameValuePair("advice", ""));
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "utf-8");
                post.setEntity(entity);
                CloseableHttpResponse resp = spider.getClient().execute(post);
                resp.close();
            }
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("text/html");
            response.setCharacterEncoding("utf-8");
            PrintWriter out = response.getWriter();
            out.println("<h1>返回刚才界面查看结果(3秒后未自动跳转,请点击<a href=\"pj.jsp\">这里</a>)</h1>");
            out.close();
            response.setHeader("refresh", "3;URL=pj.jsp");
        }
    }
}
